var $$ = function(id){return document.getElementById(id);};

var ws = new WebSocket('wss://static.zhouchun.net:5555');
var usernameInput = $$('username');
var theirUsernameInput = $$('theirUsername');
var loginButton = $$('login');
var callButton = $$('call');
var closeButton = $$('close');
var yourVideo = $$('yours');
var theirVideo = $$('theirs');
var viewer = $$('viewer');
var yourConnection;
var name = '';
var connectedUser = '';
var stream;

ws.onopen = function(){
    console.log('[onopen]连接成功');
};

ws.onerror = function(error){
    console.log('[onerror]发生错误:', error);
};

ws.onmessage = function(message){
    console.log('[onmessage]', message.data);
    var data = JSON.parse(message.data);
    switch(data.type){
        case 'login':
            onLogin(data.success);
            break;
        case 'offer':
            onOffer(data);
            break;
        case 'answer':
            onAnswer(data.answer);
            break;
        case 'candidate':
            onCandidate(data.candidate);
            break;
        case 'leave':
            onLeave();
            break;
        default:
            break;
    }
};

function send(message){
    if(connectedUser){
        message.name = connectedUser;
    }
    ws.send(JSON.stringify(message));
}

loginButton.addEventListener("click", function(event){
    name = usernameInput.value;
    if(name.length > 0){
        send({type: "login", name: name});
    }
});

callButton.addEventListener("click", function(){
    theirUsername = theirUsernameInput.value;
    if(theirUsername.length > 0){
        startPeerConnection(theirUsername);
    }
});

closeButton.addEventListener("click", function(){
    send({type: "leave"});
    onLeave();
});

function onLogin(success){
    if(success == '0'){
        alert("请输入另一个名称");
    }
    else{
        startConnection();
    }
}

function onOffer(data){
    a={};
    a.type=data.type;
    a.sdp=data.sdp;
    connectedUser = data.name;
    yourConnection.setRemoteDescription(new RTCSessionDescription(a));
    yourConnection.createAnswer(
        function(answer){
            yourConnection.setLocalDescription(answer);
            send({type: "answer", answer: answer});
        },
        function(error){
            alert("[onOffer]error");
            console.log(error);
        }
    );
}

function onAnswer(answer){
    yourConnection.setRemoteDescription(new RTCSessionDescription(answer));
}

function onCandidate(candidate){
    yourConnection.addIceCandidate(new RTCIceCandidate(candidate));
}

function onLeave(){
    connectedUser = null;
    theirVideo.src = null;
    yourConnection.close();
    yourConnection.onicecandidate = null;
    yourConnection.onaddstream = null;
    setupPeerConnection(stream);
}

function startConnection(){
    if(viewer.checked){
        stream = document.getElementById("canvas").captureStream(1);
        setupPeerConnection(stream);
    }
    else{
/*
        var constraints = {
            audio: false,
            video: {
                width: {
                    min: 1280,
                    max: 1280,
                    ideal: 1280
                },
                height: {
                    min: 720,
                    max: 720,
                    ideal: 720
                },
                frameRate: {
                    min: 20,
                    max: 25,
                    ideal: 25
                }
            }
        };
*/
        var constraints = {
            audio: false,
            video: true
        };
        navigator.mediaDevices.getUserMedia(constraints)
        .then(function(theStream){
            stream = theStream;
            //yourVideo.src = window.URL.createObjectURL(stream);
            setupPeerConnection(stream);
        })
        .catch(function(error){
            console.log(error);
        });
    }
}

function setupPeerConnection(stream){
    var configuration = {"iceServers": [{"url": "turn:106.75.15.228:3478", "username": "ling", "credential": "ling1234"}]};
    yourConnection = new RTCPeerConnection(configuration);
    if(stream){
        yourConnection.addStream(stream);
    }
    yourConnection.onaddstream = function(e){
        theirVideo.src = window.URL.createObjectURL(e.stream);
    };
    yourConnection.onicecandidate = function(event){
        if(event.candidate){
            send({type: "candidate", candidate: event.candidate});
        }
    };
}

function startPeerConnection(user){
    connectedUser = user;
    yourConnection.createOffer(
        function(offer){
            send({type: "offer", offer: offer});
            yourConnection.setLocalDescription(offer);
        },
        function(error){
            alert(error);
        }
    );
}
